//
//  WmvMyTeamVC.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import MJRefresh
import UIKit
import SVProgressHUD

// MARK: - 扩展WmvMyTeamVC + WmcNavigatorProtocol

extension WmvMyTeamVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.myTeam]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmvMyTeamVM()
        if let viewModel = parms.context as? WmvMyTeamVM {
            vm = viewModel
        }
        let vc = WmvMyTeamVC(vm)
        return vc
    }

    func willPushNavigationVC(startPushBlock: @escaping YPBlock.Empty, endOperationBlock: @escaping YPBlock.Empty) {
        if !WmcLoginManager.shared.isLogin {
            WmcLoginManager.push(animated: true) {
                WmcHudManager.toast("登录成功")
                startPushBlock()
            } failure: {
                WmcHudManager.toast("登录失败")
            }
        } else {
            startPushBlock()
        }
        YPGCD.Delay(delay: 1) {
            endOperationBlock()
        }
    }
}

// MARK: - 扩展WmvMyTeamVC + WmcVMProtocol

extension WmvMyTeamVC: WmcVMProtocol {
    typealias VMType = WmvMyTeamVM
}

// MARK: - [WmvMyTeamVC]

class WmvMyTeamVC: WmcBaseVC, WmcStatefulViewController {
    // Lifecycle

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateUploadStatus()
        setupInitialViewState()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 首次获取数据
        getData()        
        // 创建团队成功，返回次页面通知刷新
        WmcNotificationManager.shared.addObserver(type: .createTeamSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .joinTeamSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .editTeamNameSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .memberQuitTeam) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }

        WmcNotificationManager.shared.addObserver(type: .synSettingChanged) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        
        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) {[weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        
        WmcUserdefault.save(value: true, forKey: .Tips.Home.cloudAlbumNewUserGuideRedPoint)
    }

    // Internal

    lazy var mineDataBtn: WmcLeftImgRightTextBtn = {
        let btn = WmcLeftImgRightTextBtn()
        btn.imageView.image = "cloud_tabbar_mine_no".wmc_image
        btn.label.text = "个人资料"
        btn.label.font = 14.wmc_font
        btn.imgSize = 18
        btn.imgTextSpacing = 4
        btn.setTintColor(.wmc_mainTheme)
        return btn
    }()

    lazy var headView: WmcMyTeamsHeadView = {
        let view = WmcMyTeamsHeadView()
        return view
    }()

    lazy var currentEmptyView: WmcTeamMemberEmptyListView = {
        let view = WmcTeamMemberEmptyListView.emptyView(img: "cloud_album_empty", note: "暂无相册")
        return view
    }()

    /// 设置占位视图
    /// - Returns: description
    func setupPlaceholders() {
        //loadingView = WmcLoadingView()
        //emptyView = self.currentEmptyView
        //emptyView = WmcTeamAlbumListErrorView()
        let errView = WmcErrorView()
        errView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        errorView = errView
    }

    func getData() {
//        if lastState == .loading {
//            return
//        }
        //startLoading()
//        SVProgressHUD.show()
        self.viewModel.getTeams(page: 1)
    }

    override func makeUI() {
        makeNavView(style: .white, showShadow: false)
        title = "我的团队"

        self.view.backgroundColor = UIColor.wmc_gray_F7F8FA

        navView.addSubview(mineDataBtn)
        mineDataBtn.snp.makeConstraints { make in
            make.top.bottom.equalTo(navView.backImageView)
            make.right.equalTo(-16)
        }

        view.addSubview(uploadStatusView)
        view.addSubview(headView)
        view.addSubview(tableView)

        uploadStatusView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(0)
        }

        headView.snp.makeConstraints { make in
            make.top.equalTo(uploadStatusView.snp.bottom)
            make.left.right.equalToSuperview()
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }

        setupPlaceholders()
    }

    override func bindViewModel() {

        self.viewModel.listData.skip(1).bind { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
//            weakSelf.endLoading(animated: true, error: nil, completion: nil)
            weakSelf.netErrorView.removeFromSuperview()
            SVProgressHUD.dismiss()
        }.disposed(by: rx.disposeBag)

        self.viewModel.error.bind { [weak self] error in
            guard let weakSelf = self,let _ = error else { return }
//            weakSelf.endLoading(animated: true, error: error, completion: nil)
            weakSelf.addSubview(weakSelf.netErrorView)
            weakSelf.netErrorView.snp.makeConstraints { make in
                make.top.left.right.bottom.equalTo(weakSelf.tableView)
            }
            SVProgressHUD.dismiss()
        }.disposed(by: rx.disposeBag)

        /// 更新同步状态
        WmcUploadQueueManager.shared.startAutoUploadSubject.subscribe { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.updateUploadStatus()
        }.disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.completionSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.updateUploadStatus()
            weakSelf.getData()
        }).disposed(by: rx.disposeBag)

        WmcUploadQueueManager.shared.failureSubject.subscribe(onNext: { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.updateUploadStatus()
        }).disposed(by: rx.disposeBag)

        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "com.watermark.removeFromTeam"), object: nil, queue: .main) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
    }

    override func bindViewAction() {
        mineDataBtn.yp.addEvent { _ in
            WmcNavigatorManager.push(.cloudAlbumMine)
        }

        headView.createTeamBtn.rx.controlEvent(.touchUpInside).bind { _ in
            let vm = WmcCreateTeamVM()
            vm.opType = .create
            WmcNavigatorManager.push(.createTeamAlbum, parms: vm)
        }.disposed(by: rx.disposeBag)

        headView.joinTeamBtn.rx.controlEvent(.touchUpInside).bind { _ in
            WmcNavigatorManager.push(.joinTeamAblum)
        }.disposed(by: rx.disposeBag)

        uploadStatusView.rx.tapGesture().skip(1).bind { _ in
            WmcNavigatorManager.push(.uploadFailure)?.hidesBottomBarWhenPushed = true
        }.disposed(by: rx.disposeBag)
    }

    // Private

    private lazy var uploadStatusView: WmcUploadStatusView = {
        let view = WmcUploadStatusView()
        view.isHidden = true
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcMyClouddAblumCell.self, forCellReuseIdentifier: "WmcMyClouddAblumCell")
        view.register(WmcMyTeamCloudAblumCell.self, forCellReuseIdentifier: "WmcMyTeamCloudAblumCell")
        view.separatorStyle = .none
        view.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            /// 刷新
            guard let weakSelf = self else { return }
            weakSelf.getData()
            view.mj_header?.endRefreshing()
        })
        view.backgroundColor = UIColor.wmc_gray_F7F8FA
        return view
    }()
    
    lazy var netErrorView: WmcBadNetworkEmptyView = {
        let view = WmcBadNetworkEmptyView()
        view.refreshClosure = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
        return view
    }()
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmvMyTeamVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let list = self.viewModel.listData.value ?? []
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "WmcMyClouddAblumCell", for: indexPath) as! WmcMyClouddAblumCell
        let list = self.viewModel.listData.value ?? []
        let model = list[indexPath.row]
        if model.albumType == 0 {
            cell.configure(model: model)

        } else {
            cell = tableView.dequeueReusableCell(withIdentifier: "WmcMyTeamCloudAblumCell", for: indexPath) as! WmcMyTeamCloudAblumCell
            cell.configure(model: model)
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let list = self.viewModel.listData.value ?? []
        let model = list[indexPath.row]
        viewModel.updateAblumInfo(model)
        if indexPath.row == 0 {
            let vm = WmcPersonCloudAlbumTabBarVM()
            vm.teamAblum = model
            WmcNavigatorManager.push(.personCloudAlbum, parms: vm)?.hidesBottomBarWhenPushed = true
        } else {
            WmcNavigatorManager.push(.teamCloudAlbum, parms: model)
            if var count: Int = WmcUserdefault.object(forKey: .Tips.Home.enterTeamAlbumCount) {
                count = count + 1
                WmcUserdefault.save(value: count, forKey: .Tips.Home.enterTeamAlbumCount)
            } else {
                WmcUserdefault.save(value: 0, forKey: .Tips.Home.enterTeamAlbumCount)
            }
        }
        /// 跳转的时候更新红点
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.getData()
        }
    }
}

extension WmvMyTeamVC {
    /// 更新同步状态
    private func updateUploadStatus() {
        WmcUploadQueueV2DBManager.query { [weak self] list in
            guard let weakSelf = self else { return }
            var height: CGFloat = 0
            if list.count > 0 {
                height = 40
                if WmcUploadQueueManager.shared.uploading {
                    weakSelf.uploadStatusView.status = .uploading
                } else {
                    weakSelf.uploadStatusView.status = .failure
                }
            }
            if height > 0 {
                weakSelf.uploadStatusView.isHidden = false
            } else {
                weakSelf.uploadStatusView.isHidden = true
            }
            weakSelf.uploadStatusView.snp.updateConstraints { make in
                make.height.equalTo(height)
            }
        }
    }
}

extension WmvMyTeamVC {
    func hasContent() -> Bool {
        guard let list = self.viewModel.listData.value else {
            return false
        }
        return list.count > 0
    }

    func handleErrorWhenContentAvailable(_ error: Error) {
        /// 处理错误
    }
}
